/**
 * Created by no1 on 2014/9/3.
 */
'use strict';
var mysql = require('./mysql.js');
var C = require('../config/index');
var F = require('../common/function');
var MPosts = require('../model/posts.js');
var MTags = require('../model/tags.js');
var MUser = require('../model/users.js');
var Mman = require('../common/man.js');
var imgRule = require('../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./logFlow/logstash.js');
_.v = require('validator');

/*
 *@todo  API08 获取标签
 * */
exports.tags = require("./post/tags.js").tags;


/*
 *@todo API11 发布一个主题帖
 * */
exports.thread = require("./post/thread.js").thread;


/*
 *@todo  API12 回复一个主题帖
 * */
exports.post = require("./post/post.js").post;


/*
 *@todo  API14 点赞或取消点赞某主题
 * */
exports.like = require("./post/like.js").like;

/*
 *@todo  API16 收藏或取消收藏某主题
 * */
exports.fav = require("./post/fav.js").fav;


/*
 *@todo  API18 主题列表
 * */
exports.getPostList = require("./post/getPostList.js").getPostList;

/*
 * @todo API19 楼主信息(已转到api18 act=8)
 * */
exports.getThread = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  var tid = Env.I.tid;
  // 判断帖子是否存在
  var isThreadExist = yield MPosts.isThreadExist(tid);
  if (!isThreadExist) {
    return F.returnMsg(400, '帖子不存在', 1);
  }
  var manger = Env.I.manager;
  if (!(manger && manger == 1)) {
    // 判断帖子status
    var tStatus = yield mysql.queryOne('SELECT status FROM mh_thread WHERE tid=?', [tid]);
    if (tStatus['status'] == 0) {
      return F.returnMsg(400, '无效帖子', 1);
    }
  }

  var data = yield mysql.queryOne(
    'SELECT u.uid,u.nickname,u.face,t.timeline,t.digest,t.liketimes,t.closed,t.status,pc.post,p.imgext,p.pid ' +
    'FROM mh_user u ' +
    'LEFT JOIN mh_thread t ON u.uid=t.uid ' +
    'LEFT JOIN mh_post_content pc ON t.pid = pc.pid ' +
    'LEFT JOIN mh_post p ON p.tid = t.tid ' +
    'WHERE t.tid=?', [tid]);
  if (data.length < 0) {
    return F.returnMsg(400, '失败', 1);
  }

  data.like = false;
  data.friend = false;
  data.fav = false;
  //var loginStatus = yield F.isLogin(Env);
  if (loginStatus.status) {
    // 是否已点赞
    if (MPosts.isLike(data.pid, loginStatus.uid)) {
      data.like = true;
    }

    // 是否已收藏
    var isFav = yield mysql.query('SELECT uid FROM mh_fav WHERE uid=? AND tid=?', [loginStatus.uid, tid]);
    if (isFav && isFav.length > 0) {
      data.fav = true;
    }

    // 是否已关注楼主
    var isFriend = yield mysql.query('SELECT fuid FROM mh_friend WHERE uid=? AND fuid=?', [loginStatus.uid, data.uid]);
    if (isFriend && isFriend.length > 0) {
      data.friend = true;
    }
  }

  // 帖子标签
  var tagids = yield mysql.query('SELECT tagsid,tagstype,tagstitle,x,y FROM mh_thread_tags WHERE tid=?', [tid]);
  if (tagids.length > 0) {
    var tags = [];
    for (var i = 0; i < tagids.length; i++) {
      var tagsType = tagids[i].tagstype;
      var tagsid = tagids[i].tagsid;
      var tagstitle = tagids[i].tagstitle;
      var x = tagids[i].x;
      var y = tagids[i].y;
      if (tagsType == 1) {//传统标签
        var tag = yield mysql.query('SELECT tagid, tagtitle FROM mh_tags WHERE tagid=?', [tagsid]);
        if (tag.length > 0) {
          tagstitle = tag[0].tagtitle;
        }
      }
      if (Env.I.apiVerNum == 1) {
        var tagObj = {tagid: tagsid, tagtitle: tagstitle};
      }
      else {
        var tagObj = {tagsType: tagsType, tagsid: tagsid, tagstitle: tagstitle, x: x, y: y};
      }
      tags.push(tagObj);
    }
    data.tags = tags;
  }
  else {
    data.tags = [];
  }

  // 只返回前80字符的主题内容
//  if(data.post.length > 80){
//    data.post = data.post.substring(0, 80);
//  }

  data.tid = parseInt(tid);
  data.img = F.generateAttachmentUrl(data.pid, data.imgext);
  data.faceUrl = F.generateFaceUrl(data.face, data.uid);

  // 删除多余项
  delete data.face;
//  delete data.likeusers;
  delete data.imgext;
  delete data.pid;
  yield MPosts.editThread('views=views+1', 'tid=?', [tid]);//更新贴子浏览次数

  // logstash 流程
  var json = {
    uid: loginStatus.uid,
    tid: tid,
    action: 'view'
  };
  logstash.article(json);

  //更新帖子信息开始
  var key = C.redisPre.thread_info;
  key = _s.sprintf(key, parseInt(tid));
  var temp = yield F.redisCo.EXISTS(key);
  if (temp == 1) {
    F.redisClient.HINCRBY(key, 'views', 1);//帖子被浏览数+1
  }
//更新帖子信息结束
  return F.returnMsg(200, '返回主题贴成功', 3, data);
};

/*
 *@todo  API20 回帖列表
 * */
exports.getPost = require("./post/getPost.js").getPost;


/*
 *@todo  API21 标签列表
 */
exports.tagsList = require("./post/tagsList.js").tagsList;


/*
 *@todo API28	主题帖分享后回调统计接口
 * */
exports.threadShare = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  var act = fields.act;
  var tid = fields.tid;
  var type = parseInt(fields.type) > 0 ? parseInt(fields.type) : 0;  // 如参数不大于0，则设为0 未知来源
  var uid;
  if (!loginStatus.status) { // 未登录
    uid = 0;
  }
  else { // 登录
    uid = loginStatus.uid;
  }


  // 判断帖子是否存在
  var isThreadExist = yield MPosts.isThreadExist(tid);
  if (!isThreadExist) {
    return F.returnMsg(300, '帖子不存在', 3);
  }

  if (act == 1) { // 记录分享资料
    // 此主题帖分享次数+1
    mysql.query('UPDATE mh_thread SET sharetimes=sharetimes+1 WHERE tid=?', [tid]);
    //更新帖子信息开始
    var key = C.redisPre.thread_info;
    key = _s.sprintf(key, parseInt(tid));
    var temp = yield F.redisCo.EXISTS(key);
    if (temp == 1) {
      F.redisClient.HINCRBY(key, 'sharetimes', 1);//帖子被分享数+1
    }
//更新帖子信息结束
    if (loginStatus.status) {
      // 此用户分享次数+1
      mysql.query('UPDATE mh_user_info SET sharetimes=sharetimes+1 WHERE uid=?', [uid]);
      //更新分享人信息开始
      key = C.redisPre.user_info;
      key = _s.sprintf(key, parseInt(uid));
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'sharetimes', 1);//用户分享主题帖数+1
      }
      //更新分享人信息结束
    }
    mysql.query('INSERT INTO mh_share_log(tid,uid,type,timeline) VALUES(?,?,?,UNIX_TIMESTAMP())', [tid, uid, type]);
    return F.returnMsg(200, '分享记录成功', 3, {tid: tid});
  }
};

/*
 @todo API29 贴子投诉
 * 投诉: 1色情 2欺诈 3骚扰 4侮辱 5政治 6广告 7其他
 */
exports.complaintPost = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  var uid = loginStatus.uid || 0;
  var tid = 0;
  var pid = 0;
  var complain = fields.complain == undefined ? '' : fields.complain;

  if (fields.tid) {
    var threadData = yield mysql.queryOne("SELECT pid FROM mh_thread WHERE tid=?", [fields.tid]);
    if (threadData) {
      pid = threadData['pid'];
      tid = fields.tid;
    }
    else {
      return F.returnMsg(300, '你举报的帖子不存在', 1);
    }
  }
  else if (fields.pid) {
    pid = fields.pid;
    var postData = yield mysql.query('SELECT tid FROM mh_post WHERE pid=?', [pid]);
    if (postData.length == 0) {
      return F.returnMsg(300, '你举报的帖子不存在', 1);
    }
    tid = postData[0].tid;
  }
  else {
    return F.returnMsg(400, '选择你要举报的帖子', 1);
  }

  if (complain == '') {
    return F.returnMsg(400, '选择你要举报的内容', 1);
  }
  var complainArr = complain.split(',');
  var len = complainArr.length;
  for (var i = len - 1; i >= 0; i--) {
    if (!(_.v.isIn(complainArr[i], [1, 2, 3, 4, 5, 6, 7]))) {//1色情 2谣言 3网络钓鱼 4诱导分享 5政治 6广告 7其他
      complainArr.splice(i, 1);
    }
  }
  if (complainArr.length == 0) {
    return F.returnMsg(400, '选择你要举报的内容', 1);
  }

  complain = complainArr.toString();

  var flag = yield mysql.query('INSERT INTO mh_post_complain(tid,pid,uid,timeline,complain) VALUES(?,?,?,UNIX_TIMESTAMP(),?)',
    [tid, pid, uid, complain]);
  if (flag) {
    if (F.isManager(loginStatus.groupid)) {//后台人员投诉直接删帖
      if (fields.tid) {
        yield Mman.manThread(Env, {act: 1, tid: tid, tokenkey: fields.tokenkey, apiVerNum: 1, status: 0});
      }
      else if (fields.pid) {
        yield Mman.manPost(Env, {act: 1, pid: pid, tokenkey: fields.tokenkey, apiVerNum: 1, status: 0});
      }
    }
    else { //普通用户
      let c = yield mysql.queryOne('SELECT COUNT(DISTINCT mpc.uid) as num FROM mh_post_complain mpc WHERE mpc.pid= ? AND mpc.STATUS = 0',
        [pid]);
      if (c['num'] > 2) {
        if (fields.tid) {
          yield Mman.manThread(Env, {act: 1, tid: tid, tokenkey: fields.tokenkey, apiVerNum: 1, status: 0});
        }
        else if (fields.pid) {
          yield Mman.manPost(Env, {act: 1, pid: pid, tokenkey: fields.tokenkey, apiVerNum: 1, status: 0});
        }
      }
    }
    return F.returnMsg(200, '举报成功', 1);
  }
};

/*
 @todo API30 刷新又拍云图片
 * 通知又拍云服务器刷下图片
 */
exports.upyunPurge = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  var uid = loginStatus.uid || 0;
  if (fields.act == 1 && fields.url) {
    var imgurl = fields.url;
    //var bucket=C.upyun.bucket||'inmm-img';
    //var purge_url=C.upyun.purge_url||'http://purge.upyun.com/purge/';
    //var user=C.upyun.user||'inmm01';
    //var passwordmd5=C.upyun.token;
    //var now = new Date();
    //var date = now.toUTCString();
    //var sign = md5.digest_s(imgurl+'&'+bucket+'&'+date+'&'+passwordmd5);
    //var options={
    //  url: purge_url,
    //  headers: {
    //    'Expect': '',
    //      'Authorization': 'UpYun '+bucket+':'+user+':'+sign,
    //    'Date': date
    //  },
    //  timeout: 30,
    //  method: 'POST',
    //  form: {
    //    purge: encodeURIComponent(imgurl)
    //  }
    //};
    //async_request.post(options,function callback(error, response, body) {
    //  if (!error && response.statusCode == 200) {
    //    console.log(response);
    //  }else{
    //    console.log(error);
    //  }
    //});
    F.upyun.purge([imgurl], function () {
    });
    mysql.query('INSERT INTO mh_losturl(losturl, uid) values(?,?)', [imgurl, uid]);
    return F.returnMsg(200, '已提交更新', 3);
  }
  return F.returnMsg(400, '传递的参数错误', 1);
};

/**
 * @todo API31 帖子图片上传成功后的Callback
 * @param Env
 * @returns {*}
 */
exports.imgCallback = require("./post/imgCallback.js").imgCallback;

/**
 * @todo API32 取轮播
 * @param Env
 * @returns {*}
 */
exports.getSlider = require("./post/getSlider.js").getSlider;

/**
 * @todo API37 删除主题帖、回帖
 * @param Env
 * @returns {*}
 */
exports.delPost = require("./post/delPost.js").delPost;

/*
 *@todo API38	主题帖分享后回调统计接口
 * */
exports.shareCallback = require("./post/shareCallback.js").shareCallback;


/*
 *@todo API40	省市列表
 * */

exports.cityList = function*(Env) {
  var fields = Env.I;
  var act = fields.act;
  var parentid = fields.parentid;
  if (act == 2) {
    if (!parentid) {
      return F.returnMsg(400, '传递的参数错误，必须传入parentid参数.', 1);
    }
    else {
      var pattern = /^(\d+,)*\d+$/;
      if (!pattern.test(parentid))
        return F.returnMsg(400, '传递的parentid参数有误，请检查.', 1);
    }
  }

  //var citylist = yield mysql.query('SELECT provincecode,province,citycode,city FROM mh_district ORDER BY id');
  if (act == 1) { // 返回省市列表
    var cityInfo = F.getCityInfo();
    var citylist = [];
    for (var cid in cityInfo) {
      citylist.push({
        provincecode: cityInfo[cid].provincecode,
        province: cityInfo[cid].province,
        citycode: cityInfo[cid].citycode,
        city: cityInfo[cid].city
      });
    }
    return F.returnMsg(200, '成功', 3, {citylist: citylist})
  }
  else if (act == 2) {//返回省市区街道四级列表
    var parentarray = parentid.split(',');
    for (var id in parentarray) {
      parentarray[id] = parseInt(parentarray[id]);
    }
    var tempData = [];
    tempData = yield mysql.query('select region_id,region_name,region_type,parent_id from mh_region where parent_id in (' + parentarray.join() + ')');
    if (tempData.length == 0) {
      return F.returnMsg(300, '没有数据', 3);
    }
    if (parentarray.length == 0) {
      return F.returnMsg(200, '成功', 3, {regionlist: [tempData]});
    }
    else {
      var region = [];
      for (var id in parentarray) {
        region.push(_.filter(tempData, function (temp) {
          return temp['parent_id'] == parentarray[id];
        }));
      }
      return F.returnMsg(200, '成功', 3, {regionlist: region});
    }
  }
  else {
    return F.returnMsg(400, '传递的参数错误', 1)
  }


};


/**
 * 根据用户帖子内容，自动推荐分类
 * @param Env
 */
exports.getautoCate =function*(Env){
  let fields = Env.I;
  let act = fields.act||1;
  let post = _s.trim(fields.post);
  if(!post){
    return F.returnMsg(200, '获取推荐分类成功', 3, {intelligent:[C.autocate.default_cate]});
  }
  let info =[];
  try{
    info = yield F.autoCate(post);
    console.log(info);
    //出现服务器异常才会返回一个长度数组
    if(info.length==1){
      return F.returnMsg(200, '获取推荐分类成功', 3, {intelligent:[C.autocate.default_cate]});
    }
  }catch(err){
    console.log(err);
  }
    //获取id
    let idsArray =[];
    //取可能性不低于配置项的推荐记录，同时过滤掉配置项里面的内部圈子；
    for(let index in info){
      let cid=parseInt(info[index][0]);
      let percent=parseFloat(info[index][1]);
      if(percent>=C.autocate.percent){
        let tmpObj= yield  mysql.queryOne('select cid,name,pcid from mh_thread_category where cid=?',[cid]);
        console.log(tmpObj);
        if(!_.v.isIn(tmpObj.pcid,C.autocate.inner_cate)){
          if(tmpObj.cid==6){
            tmpObj.cid=16; //娱乐圈子id的bug
          }
          idsArray.push({name:tmpObj.name,cid:tmpObj.cid});
        }
      }else {
        break;
      }
    }
    //模拟过滤结果为空
    //idsArray=[];
    //如果过滤结果为空，加入默认配置推荐
    if(idsArray.length==0){
      console.log('----过滤结果为空的情形-------');
      idsArray.push(C.autocate.default_cate);
    }
    return F.returnMsg(200, '获取推荐分类成功', 3, {intelligent:idsArray});

};


/**
 * @todo API57 统计帖子里面图片/视频，或用户头像点击量
 * @param Env
 */
exports.countMeidaViews = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  let act = fields.act;
  var id = 0;//初始化id值，如果act=1或2，id值为TH或P的值，如果act=3,id值为A的值，否则为0；
  //分解I.head_mark
  let head_mark = fields.head_mark;
  let mark = head_mark.mark;
  let decodemark = head_mark.decodemark;
  //检验动作类型
  if (!_.v.isIn(act, [1, 2, 3])) {
    return F.returnMsg(400, '传递的参数错误', 1);
  }
  let type = act;//act 1 点击图片 2 点击视频 3 点击用户头像
  //用户登录uid
  let uid = loginStatus.uid || 0;

  //获取操作用户的device_id
  let device_id = {device_id: '', type: 0};
  device_id.device_id = fields['device_id']['device_id'] || '';
  device_id.type = fields['device_id']['type'] || 0;
  device_id = JSON.stringify(device_id);

  //定义mark里面包含的可选变量
  let range=['S','W','V','TH','P','A','T','H','SP','TB','TM','SD','C','O','UM','PG'];

  //mark与decodemark均不为空情况下，记录浏览信息并入库
  if(mark.length>0 && !_.isEmpty(decodemark)){
    console.log('开始检查mark')
    //过滤无效参数
    var tmpArr=[];
    for(var key  in  decodemark){
      if(!_.v.isIn(key,range) || (key!='C' && parseInt(decodemark[key])==0)){
        delete decodemark[key];
      }else{
        tmpArr.push(key+decodemark[key]);
      }
      //当点击图片或视频时，初始化id值
      if(act!=3){
        if(key=='TH'|| key=='P'){
          id = parseInt(decodemark[key]);
        }
      }
    }

    //如果点击的是图片或视频，根据TH或P确定id值
    if(_.has(decodemark,'TH') && act!=3){
      if(_.has(decodemark,'P')){
        id = decodemark['P'];//点击帖子下面的回帖图片
      }else{
        id = decodemark['TH'];
      }
    }

    //如果点击的是头像，根据A的值决定id值
    if(_.has(decodemark,'A') && act==3){
      id = decodemark['A'];
    }
    console.log(decodemark);
    mark = tmpArr.join(':');
    console.log(mark);
    //写入信息统计
    let tag = yield F.writeMediaviewLog(type, uid, id, device_id, mark);
    if (tag.success) {
      return F.returnMsg(200, '浏览量统计成功', 3, {type: type, uid: uid, id: id, device_id: device_id, mark: mark});
    }else{
      return F.returnMsg(400, tag.info, 1);
    }
  }
  //当没有mark时或mark为空，给出一个默认结果
  return F.returnMsg(200, '浏览量统计成功', 3, {type: type, uid: uid, id: id, device_id: device_id, mark: mark});
};


/**
 * @ API59 获取o2o商品多级分类
 */
exports.geto2oCate = function*(){
  //获取多级数据：{act:2,deep:3}
  let data =　yield F.geto2oCategoryList({act:2,type:3,depth:3},"list");
  data =data.result;
  return F.returnMsg(200,'获取分类列表成功',3,data);
};

/**
 * @ API61 获取瓷肌百科页面
 */
exports.getCiJiWiki = function*(Env){
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  let act = fields.act;
  let id=fields.id;
  let type=fields.type;
  if(!_.v.isInt(id)){
    return F.returnMsg(400,'id输入有误',1);
  }
  if(!_.v.isInt(type)){
    return F.returnMsg(400,'type输入有误',1);
  }
  let wikiSection= require('../model/mWikiPage');
  let result= yield wikiSection.getPageByTypeNId(type,id,1);
  if(result.status==300){
    return F.returnMsg(300,result['message'].msg,1);
  }else{
    return F.returnMsg(200,'成功',3,result);
  }
};
